/*
 * @Author: Zhengxuan Ye
 * @Date: 2025-05-06 21:28:51
 * @Last Modified by:   Zhengxuan Ye
 * @Last Modified time: 2025-05-06 21:28:51
 */

import { defineStore } from 'pinia'
import axios from 'axios'

// API基础URL
const API_URL = 'http://localhost:3000/api'

export const useAdminStore = defineStore('admin', {
  state: () => ({
    interactionStats: [],
    users: [],
    loading: false,
    error: null,
  }),

  actions: {
    // 获取交互统计数据
    async getInteractionStats(token) {
      try {
        this.loading = true
        console.log('获取交互统计数据')

        const response = await axios.get(`${API_URL}/interaction/stats`, {
          headers: { Authorization: `Bearer ${token}` },
          withCredentials: true,
        })

        console.log('交互统计数据响应:', response.data)
        this.interactionStats = response.data.stats || []
        this.loading = false
        return this.interactionStats
      } catch (error) {
        console.error('获取交互统计数据失败:', error)
        this.error = error.response?.data?.message || '获取交互统计数据失败'
        this.loading = false
        return []
      }
    },

    // 获取页面评论
    async getPageComments(pageId, token) {
      try {
        this.loading = true
        console.log(`获取页面 ${pageId} 的评论`)

        const response = await axios.get(`${API_URL}/interaction/comments/${pageId}`, {
          headers: token ? { Authorization: `Bearer ${token}` } : {},
          withCredentials: true,
        })

        console.log('评论响应:', response.data)
        this.loading = false
        return response.data.comments || []
      } catch (error) {
        console.error(`获取页面 ${pageId} 的评论失败:`, error)
        this.error = error.response?.data?.message || '获取评论失败'
        this.loading = false
        return []
      }
    },

    // 删除评论
    async deleteComment(commentId, token) {
      try {
        this.loading = true
        console.log(`删除评论 ${commentId}`)

        const response = await axios.delete(`${API_URL}/interaction/comment/${commentId}`, {
          headers: { Authorization: `Bearer ${token}` },
          withCredentials: true,
        })

        console.log('删除评论响应:', response.data)
        this.loading = false
        return true
      } catch (error) {
        console.error(`删除评论 ${commentId} 失败:`, error)
        this.error = error.response?.data?.message || '删除评论失败'
        this.loading = false
        return false
      }
    },

    // 获取用户列表
    async getUsers(token) {
      try {
        this.loading = true
        console.log('获取用户列表')

        // 这里需要后端提供获取用户列表的API
        // 暂时返回空数组
        this.users = []
        this.loading = false
        return this.users
      } catch (error) {
        console.error('获取用户列表失败:', error)
        this.error = error.response?.data?.message || '获取用户列表失败'
        this.loading = false
        return []
      }
    },

    // 重置错误状态
    resetError() {
      this.error = null
    },
  },
})
